<template>
  <div>

    <div class="i_bg">
      <div class="content mar_20">
        <img src="@/assets/images/img2.jpg" />
      </div>

      <!--Begin 第二步：确认订单信息 Begin -->
      <div class="content mar_20">
        <div class="two_bg">
          <div class="two_t">
            <span class="fr">
              <a href="#" @click.prevent="checkUpdate()" v-show="!isDelete">修改</a>
              <a href="#" @click.prevent="checkUpdate()" v-show="isDelete">取消</a>
            </span>商品列表
          </div>
          <table border="0" class="car_tab" style="width:1110px;" cellspacing="0" cellpadding="0">
            <tr>
              <td class="car_th" width="550">商品名称</td>
              <td class="car_th" width="140">属性</td>
              <td class="car_th" width="150">购买数量</td>
              <td class="car_th" width="130">小计</td>
            </tr>
            <tr v-for="buyCar in pageInfo.list" :key="buyCar.id">
              <td>
                <div class="c_s_img"><img :src="'http://192.168.144.183:9090/easybuyImages/' + buyCar.product.fileName"
                    width="73" height="73" /></div>
                {{ buyCar.product.name }}
              </td>
              <td align="center">颜色：灰色</td>
              <td align="center">{{ buyCar.number }}</td>
              <td align="center" style="color:#ff4e00;">￥{{ (buyCar.number * buyCar.product.price).toFixed(2) }}
                &nbsp;&nbsp;<span v-show="isDelete" @click="delBuyCar(buyCar.id)">删除</span>
              </td>

            </tr>

            <tr style="height: 20px;">
              <td colspan="4">
                <span class="pagination">
                  <span>
                    <span>共{{ pageInfo.total }}条数据</span>&nbsp;&nbsp;
                    <span>第{{ pageInfo.pageNum }}/{{ pageInfo.pages }}页</span>&nbsp;&nbsp;
                  </span>
                  <span>
                    <a href="#" @click.prevent="getPage('home')">首页</a>&nbsp;&nbsp;
                    <a href="#" @click.prevent="getPage('last')">上一页</a>&nbsp;&nbsp;
                    <a href="#" @click.prevent="getPage('next')">下一页</a>&nbsp;&nbsp;
                    <a href="#" @click.prevent="getPage('end')">末页</a>
                  </span>
                </span>
              </td>
            </tr>
            <tr>
              <td colspan="5" align="right" style="font-family:'Microsoft YaHei';">
                商品总价：￥{{ getTotalPrice() }}
              </td>
            </tr>
          </table>

          <div>
            <div class="two_t">
              <span class="fr">
                <a href="#" @click.prevent="checkUpdateAddress()" v-show="isUpdateAddress">修改</a>
                <a href="#" @click.prevent="cancalAddressShow()" v-show="!isUpdateAddress">取消</a>
              </span>收货人信息
            </div>
            <div v-show="isUpdateAddress">
              <div v-if="addressInfo !== null">
                <table border="0" class="peo_tab" style="width:1110px;" cellspacing="0" cellpadding="0">
                  <tr>
                    <td class="p_td" width="160">收货人姓名</td>
                    <td width="395">{{ addressInfo.userName }}</td>
                    <td class="p_td" width="160">电子邮件</td>
                    <td width="395">{{ addressInfo.email }}</td>
                  </tr>
                  <tr>
                    <td class="p_td">详细信息</td>
                    <td>{{ addressInfo.address }}</td>

                    <td class="p_td">手机</td>
                    <td>{{ addressInfo.mobile }}</td>
                  </tr>
                </table>
              </div>

              <span v-else style="width: 100%; margin-left: 10%; font-size: 16px;">
                暂无收货地址，请<a href="#" @click.prevent="toMemberAddress()">添加</a>
              </span>
            </div>
          </div>

          <div v-show="checkAddrss">

            <table border="0" class="peo_tab" style="width:1110px;" cellspacing="0" cellpadding="0"
              v-if="userAddress != null && userAddress.length > 0">
              <tr>
                <td style="background-color: #f6f6f6;">收货人姓名</td>
                <td style="background-color: #f6f6f6;">详细地址</td>
                <td style="background-color: #f6f6f6;">电子邮件</td>
                <td style="background-color: #f6f6f6;">手机</td>
                <td style="background-color: #f6f6f6;">操作</td>
              </tr>
              <tr v-for="address in userAddress" :key="address.id">
                <td>{{ address.userName }}</td>
                <td>{{ address.address }}</td>
                <td>{{ address.email }}</td>
                <td>{{ address.mobile }}</td>
                <td><a @click.prevent="chooseAddress(address)" style="color: #ff4e00;">选择</a></td>
              </tr>
            </table>
            <div v-else style="width: 100%; margin-left: 10%; font-size: 16px;">
              <p>
                暂无收货地址，请<a href="#" @click.prevent="toMemberAddress()">添加</a>
              </p>
            </div>
          </div>


          <table border="0" style="width:900px; margin-top:20px;" cellspacing="0" cellpadding="0">
            <!-- <tr>
              <td align="right">
                该订单完成后，您将获得 <font color="#ff4e00">1815</font> 积分 ，以及价值 <font color="#ff4e00">￥0.00</font> 的红包 <br />
                商品总价: <font color="#ff4e00">￥1815.00</font> + 配送费用: <font color="#ff4e00">￥15.00</font>
              </td>
            </tr> -->
            <tr height="70">
              <td align="right">
                <b style="font-size:14px;">应付款金额：<span style="font-size:22px; color:#ff4e00;">￥{{ getTotalPrice()
                }}</span></b>
              </td>
            </tr>
            <tr height="70">
              <td align="right"><a href="#" @click.prevent="toAddOrder()"><img src="@/assets/images/btn_sure.gif" /></a>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'BuyCarTwoView',
  data() {
    return {
      userId: '',
      user: '',
      buyCarList: [],
      pageInfo: null,
      addressInfo: null,
      userAddress: [],
      isDelete: false,
      isUpdateAddress: true,
      checkAddrss: false,
      payMethod: 'wechat'
    }
  },
  methods: {
    ...mapMutations(['setShowPage']),
    getAllBuyCar(pageNum, pageSize) {
      this.$axios({
        url: 'selectBuyCarByPage',
        method: 'post',
        data: {
          pageNum: pageNum,
          pageSize: pageSize,
          userId: this.userId
        },
        headers: {
          'content-type': 'application/json'
        }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          this.pageInfo = rs.data.pageInfo
          console.log(this.pageInfo)
          console.log(this.pageInfo.list.length)
        }
      })
    },
    toMemberAddress() {
      this.$router.push('/memberAddress')
    },
    getPage(opr) {
      let pageNum = 1
      switch (opr) {
        case 'last':
          pageNum = this.pageInfo.prePage === 0 ? 1 : this.pageInfo.prePage
          break
        case 'next':
          pageNum = this.pageInfo.nextPage === 0 ? this.pageInfo.pages : this.pageInfo.nextPage
          break
        case 'end':
          pageNum = this.pageInfo.pages
          break
      }
      this.getAllBuyCar(pageNum, 5)
      this.getBuyCars()
    },
    getTotalPrice() {
      this.totalPrice = 0;
      for (let buyCar of this.buyCarList) {
        let count = buyCar.number * buyCar.product.price
        this.totalPrice = this.totalPrice + count
      }
      return this.totalPrice.toFixed(2)
    },
    getDefaultAddress() {
      this.$axios({
        url: 'selectDefaultAddress',
        method: 'get',
        params: { userId: this.userId }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          this.addressInfo = rs.data.defaultAddress
        }
      })
    },
    delBuyCar(id) {
      if (confirm('是否删除？')) {
        this.$axios({
          url: 'deleteBuyCar',
          method: 'get',
          params: { id: id }
        }).then(rs => {
          if (rs.data.code == 5200 || rs.data.code == '5200') {
            alert('删除成功！')
            this.getAllBuyCar(1, 5)
            this.getBuyCars()
          } else {
            alert('删除失败！')
          }
        })
      }
    },
    checkUpdate() {
      if (this.isDelete == false) {
        this.isDelete = true
      } else {
        this.isDelete = false
      }
    },
    checkUpdateAddress() {
      this.isUpdateAddress = false
      this.checkAddrss = true
    },
    chooseAddress(address) {
      this.addressInfo = address
      this.checkAddrss = false
      this.isUpdateAddress = true
    },
    getUserAddress() {
      this.$axios({
        url: 'selectAddressByUserId',
        method: 'get',
        params: { userId: this.userId }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          this.userAddress = rs.data.userAddress
        }
      })
    },
    cancalAddressShow() {
      this.isUpdateAddress = true
      this.checkAddrss = false
    },
    toBuyCarThree() {
      this.$router.push('/buycarThree')
    },
    getUser() {
      this.$axios({
        url: 'selectUserById',
        method: 'get',
        params: { id: this.userId }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          this.user = rs.data.user
        }
      })
    },

    toAddOrder() {
      if (this.addressInfo == '' || this.addressInfo == null) {
        alert('请选择地址！')
        return
      }
      if (this.payMethod == '') {
        alert('请选择支付方式！')
        return
      }
      if (this.buyCarList.length == 0) {
        alert('请选择商品！')
        return
      }
      if (this.getTotalPrice() == 0) {
        alert('请选择商品！')
      }
      this.$axios({
        url: 'addOrder',
        method: 'post',
        data: {
          userId: this.userId,
          loginName: this.user.loginName,
          userAddress: this.addressInfo.address,
          cost: this.getTotalPrice(),
          orderDetialList: this.buyCarList.map(item => ({
            productId: item.pid,
            quantity: item.number,
            cost: item.number * item.product.price
          }))
        },
        headers: {
          'content-type': 'application/json'
        }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          let orderId = rs.data.orderId
          this.deleteAll()
          alert('生成订单成功！')
          this.$router.push({ path: '/buycarThree', query: { orderId: orderId } })
        } else {
          alert('生成订单失败！')
        }
      })
    },
    getBuyCars() {
      this.$axios({
        url: 'selectAllBuyCar',
        params: {
          userId: this.userId
        }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          this.buyCarList = rs.data.allBuyCar
        }
      })
    },
    deleteAll() {
      this.$axios({
        url: 'deleteBuyCarByUserId',
        method: 'get',
        params: { userId: this.userId }
      }).then(rs => {
        if (rs.data.code == 5200 || rs.data.code == '5200') {
          return
        } else {
          return
        }
      })
    },
  },
  mounted() {
    this.userId = window.sessionStorage.getItem('userId')
    this.getUser()
    this.getAllBuyCar(1, 5)
    this.getBuyCars()
    this.getDefaultAddress()
    this.getUserAddress()
    this.setShowPage(0)
  }
}
</script>
<style scoped>
.check {
  height: 36px;
  line-height: 36px;
  color: white;
  padding: 0 24px;
  overflow: hidden;
  border: 2px solid #ff4e00;
  background-color: #ff4e00;
}

.pagination {
  text-align: center;
  display: block;
}
</style>
